/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * MovTst.java
 *
 * Created on 04/08/2009, 16:45:46
 */
package br.com.sismovimentacao.view;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.beans.Beans;
import java.util.ArrayList;
import java.text.*;
import java.util.Date;
import java.util.List;
import javax.persistence.RollbackException;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;


/**
 *
 * @author lac
 */
public class MovTst extends JFrame {

    public static MovTst m;
    public Thread thread;

    public MovTst() {
        initComponents();
        teclasDeAtalho();
        if (!Beans.isDesignTime()) {
            entityManager.getTransaction().begin();
        }
        this.motoristaComboBox.setSelectedIndex(-1);
        this.destinoComboBox.setSelectedIndex(-1);
        jLabel6.setVisible(false);
        masterTable.setCursor(Cursor.getPredefinedCursor(12));
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        entityManager = java.beans.Beans.isDesignTime() ? null : javax.persistence.Persistence.createEntityManagerFactory("db_movimentacaoPU").createEntityManager();
        query = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT m FROM Movimentacao m WHERE m.mvlfech='0'");
        list = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(query.getResultList());
        viaturaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT v FROM Viatura v \nORDER BY v.vtcmodl");
        viaturaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(viaturaQuery.getResultList());
        MotoristaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM Pessoa p, PessoaTipo t  \nWHERE p.psncodg = t.psncodg  \nAND t.tpncodg = '1' \nORDER BY p.pscdesc");
        MotoristaList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(MotoristaQuery.getResultList());
        destinoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT d FROM Destino d\nORDER BY d.dtcdesc");
        destinoList = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : destinoQuery.getResultList();
        destinoListCellRenderer1 = new br.com.sismovimentacao.renderer.DestinoListCellRenderer();
        pessoaListCellRenderer1 = new br.com.sismovimentacao.renderer.PessoaListCellRenderer();
        viaturaListCellRenderer1 = new br.com.sismovimentacao.renderer.ViaturaListCellRenderer();
        viaturaOdomListRedender1 = new br.com.sismovimentacao.renderer.ViaturaOdomListRedender();
        jPanel3 = new javax.swing.JPanel();
        jPanel1 = new javax.swing.JPanel();
        vtncodgLabel = new javax.swing.JLabel();
        psncodgLabel = new javax.swing.JLabel();
        dtncodgLabel = new javax.swing.JLabel();
        mvtinicLabel = new javax.swing.JLabel();
        mvddinicLabel = new javax.swing.JLabel();
        mvnoiniLabel = new javax.swing.JLabel();
        mvcfinlLabel = new javax.swing.JLabel();
        mvnoiniField = new javax.swing.JTextField();
        finalidadeField = new javax.swing.JTextField();
        viaturaComboBox = new javax.swing.JComboBox();
        motoristaComboBox = new javax.swing.JComboBox();
        destinoComboBox = new javax.swing.JComboBox();
        mvtinicField = new javax.swing.JFormattedTextField();
        mvddinicField = new javax.swing.JFormattedTextField();
        esperarBusyViatura = new org.jdesktop.swingx.JXBusyLabel();
        esperarBusyMotorista = new org.jdesktop.swingx.JXBusyLabel();
        esperarBusyDestino = new org.jdesktop.swingx.JXBusyLabel();
        esperarBusyFinalidade = new org.jdesktop.swingx.JXBusyLabel();
        jPanel2 = new javax.swing.JPanel();
        jToolBar1 = new javax.swing.JToolBar();
        newButton = new javax.swing.JButton();
        refreshButton = new javax.swing.JButton();
        saveButton = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        masterScrollPane = new javax.swing.JScrollPane();
        masterTable = new javax.swing.JTable();
        minimizarLabel = new javax.swing.JLabel();
        jPanel4 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        logofButton = new javax.swing.JButton();
        fecharButton = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();

        FormListener formListener = new FormListener();

        destinoListCellRenderer1.setText("destinoListCellRenderer1");

        pessoaListCellRenderer1.setText("pessoaListCellRenderer1");

        viaturaListCellRenderer1.setText("viaturaListCellRenderer1");

        viaturaOdomListRedender1.setText("viaturaOdomListRedender1");

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Controle de Viatura");
        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));
        setMinimumSize(new java.awt.Dimension(800, 600));
        setResizable(false);
        setUndecorated(true);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jPanel1.setEnabled(false);
        jPanel1.setFont(new java.awt.Font("Tahoma", 0, 18));

        vtncodgLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        vtncodgLabel.setText("Viatura:");
        vtncodgLabel.setDoubleBuffered(true);

        psncodgLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        psncodgLabel.setText("Motorista:");

        dtncodgLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        dtncodgLabel.setText("Destino:");

        mvtinicLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        mvtinicLabel.setText("Hora de Saída:");

        mvddinicLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        mvddinicLabel.setText("Data de Saída:");

        mvnoiniLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        mvnoiniLabel.setText("Hodômetro Saída:");

        mvcfinlLabel.setFont(new java.awt.Font("Tahoma", 0, 18));
        mvcfinlLabel.setText("Finalidade:");

        mvnoiniField.setEditable(false);
        mvnoiniField.setFont(new java.awt.Font("Tahoma", 0, 18));
        mvnoiniField.setEnabled(false);

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.vtncodg.vtnodom}"), mvnoiniField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);

        finalidadeField.setFont(new java.awt.Font("Tahoma", 0, 18));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.mvcfinl}"), finalidadeField, org.jdesktop.beansbinding.BeanProperty.create("text"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement != null}"), finalidadeField, org.jdesktop.beansbinding.BeanProperty.create("enabled"));
        bindingGroup.addBinding(binding);

        finalidadeField.addActionListener(formListener);
        finalidadeField.addFocusListener(formListener);
        finalidadeField.addKeyListener(formListener);

        viaturaComboBox.setFont(new java.awt.Font("Tahoma", 0, 18));
        viaturaComboBox.setEditor(null);
        viaturaComboBox.setEnabled(false);
        viaturaComboBox.setOpaque(false);
        viaturaComboBox.setRenderer(viaturaListCellRenderer1);
        viaturaComboBox.setRequestFocusEnabled(false);

        org.jdesktop.swingbinding.JComboBoxBinding jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, viaturaList, viaturaComboBox);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.vtncodg}"), viaturaComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        binding.setSourceUnreadableValue(null);
        bindingGroup.addBinding(binding);

        viaturaComboBox.addMouseListener(formListener);
        viaturaComboBox.addActionListener(formListener);
        viaturaComboBox.addKeyListener(formListener);

        motoristaComboBox.setFont(new java.awt.Font("Tahoma", 0, 18));
        motoristaComboBox.setEditor(null);
        motoristaComboBox.setEnabled(false);
        motoristaComboBox.setRenderer(pessoaListCellRenderer1);
        motoristaComboBox.setRequestFocusEnabled(false);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, MotoristaList, motoristaComboBox);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.psncodg}"), motoristaComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        motoristaComboBox.addMouseListener(formListener);
        motoristaComboBox.addActionListener(formListener);
        motoristaComboBox.addKeyListener(formListener);

        destinoComboBox.setFont(new java.awt.Font("Tahoma", 0, 18));
        destinoComboBox.setEditor(null);
        destinoComboBox.setEnabled(false);
        destinoComboBox.setRenderer(destinoListCellRenderer1);
        destinoComboBox.setRequestFocusEnabled(false);

        jComboBoxBinding = org.jdesktop.swingbinding.SwingBindings.createJComboBoxBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, destinoList, destinoComboBox);
        bindingGroup.addBinding(jComboBoxBinding);
        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.dtncodg}"), destinoComboBox, org.jdesktop.beansbinding.BeanProperty.create("selectedItem"));
        bindingGroup.addBinding(binding);

        destinoComboBox.addMouseListener(formListener);
        destinoComboBox.addActionListener(formListener);
        destinoComboBox.addKeyListener(formListener);

        mvtinicField.setEditable(false);
        mvtinicField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(java.text.DateFormat.getTimeInstance(java.text.DateFormat.MEDIUM))));
        mvtinicField.setEnabled(false);
        mvtinicField.setFont(new java.awt.Font("Tahoma", 0, 18));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.mvtinic}"), mvtinicField, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        mvddinicField.setEditable(false);
        mvddinicField.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter()));
        mvddinicField.setEnabled(false);
        mvddinicField.setFont(new java.awt.Font("Tahoma", 0, 18));

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, masterTable, org.jdesktop.beansbinding.ELProperty.create("${selectedElement.mvddinic}"), mvddinicField, org.jdesktop.beansbinding.BeanProperty.create("value"));
        bindingGroup.addBinding(binding);

        esperarBusyViatura.setBusy(true);
        esperarBusyViatura.setEnabled(false);
        esperarBusyViatura.setFocusable(false);

        esperarBusyMotorista.setBusy(true);
        esperarBusyMotorista.setEnabled(false);
        esperarBusyMotorista.setFocusable(false);

        esperarBusyDestino.setBusy(true);
        esperarBusyDestino.setEnabled(false);
        esperarBusyDestino.setFocusable(false);

        esperarBusyFinalidade.setBusy(true);
        esperarBusyFinalidade.setEnabled(false);
        esperarBusyFinalidade.setFocusable(false);

        jToolBar1.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        jToolBar1.setFloatable(false);

        newButton.setFont(new java.awt.Font("Tahoma", 1, 12));
        newButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/sismovimentacao/img/add.png"))); // NOI18N
        newButton.setText("<html><font size= 3><b>Novo</font><font size=1> (F5)");
        newButton.setToolTipText("Abrir uma nova ocorrência");
        newButton.setFocusable(false);
        newButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        newButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        newButton.addActionListener(formListener);
        jToolBar1.add(newButton);

        refreshButton.setFont(new java.awt.Font("Tahoma", 1, 12));
        refreshButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/sismovimentacao/img/gtk-cancel.png"))); // NOI18N
        refreshButton.setText("<html><font size= 3><b>Cancelar</font><font size=1> (Esc)");
        refreshButton.setToolTipText("Cancelar uma ocorrência não salva");
        refreshButton.setEnabled(false);
        refreshButton.setFocusable(false);
        refreshButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        refreshButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        refreshButton.addActionListener(formListener);
        jToolBar1.add(refreshButton);

        saveButton.setFont(new java.awt.Font("Tahoma", 1, 12));
        saveButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/br/com/sismovimentacao/img/go-next.png"))); // NOI18N
        saveButton.setText("<html><font size= 3><b>Salvar</font><font size=1> (Enter)");
        saveButton.setToolTipText("Salvar ocorrência");
        saveButton.setEnabled(false);
        saveButton.setFocusable(false);
        saveButton.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        saveButton.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        saveButton.addActionListener(formListener);
        jToolBar1.add(saveButton);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(36, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 119, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addGap(19, 19, 19)
                                        .addComponent(dtncodgLabel))
                                    .addComponent(mvcfinlLabel)
                                    .addComponent(vtncodgLabel, javax.swing.GroupLayout.Alignment.TRAILING))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(viaturaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 240, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(esperarBusyViatura, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(psncodgLabel)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(motoristaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 234, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addComponent(destinoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 610, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(finalidadeField, javax.swing.GroupLayout.PREFERRED_SIZE, 610, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(mvtinicLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(mvtinicField, javax.swing.GroupLayout.PREFERRED_SIZE, 92, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(mvddinicLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(mvddinicField, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                .addComponent(mvnoiniLabel)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(mvnoiniField, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(esperarBusyFinalidade, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                            .addComponent(esperarBusyMotorista, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)
                            .addComponent(esperarBusyDestino, javax.swing.GroupLayout.DEFAULT_SIZE, 44, Short.MAX_VALUE)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(202, 202, 202)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(esperarBusyMotorista, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(esperarBusyDestino, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(esperarBusyFinalidade, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(vtncodgLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 29, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(viaturaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(motoristaComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addComponent(psncodgLabel))
                            .addComponent(esperarBusyViatura, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(dtncodgLabel)
                            .addComponent(destinoComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(mvcfinlLabel)
                            .addComponent(finalidadeField, javax.swing.GroupLayout.PREFERRED_SIZE, 38, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(mvtinicLabel)
                            .addComponent(mvtinicField, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(mvddinicLabel)
                            .addComponent(mvddinicField, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(mvnoiniLabel)
                            .addComponent(mvnoiniField, javax.swing.GroupLayout.PREFERRED_SIZE, 36, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 129, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jPanel5.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ocorrências Abertas", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 18))); // NOI18N
        jPanel5.setFocusable(false);

        masterTable.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        masterTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        masterTable.setFocusable(false);
        masterTable.getTableHeader().setReorderingAllowed(false);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, list, masterTable);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvlfech}"));
        columnBinding.setColumnName("<html><font size=3 color=red><center><b>FECHAR</html>");
        columnBinding.setColumnClass(Boolean.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${vtncodg.vtcmodl}"));
        columnBinding.setColumnName("Viatura");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${psncodg.pscdesc}"));
        columnBinding.setColumnName("Motorista");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${dtncodg.dtcdesc}"));
        columnBinding.setColumnName("Destino");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvtinic}"));
        columnBinding.setColumnName("Hora Saida");
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvddinic}"));
        columnBinding.setColumnName("Data Saida");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvtfinl}"));
        columnBinding.setColumnName("Hora Chegada");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvddfinl}"));
        columnBinding.setColumnName("Data Chegada");
        columnBinding.setColumnClass(java.util.Date.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvnoini}"));
        columnBinding.setColumnName("Hodômetro Saida");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvnofin}"));
        columnBinding.setColumnName("Hodômetro Chegada");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvcfinl}"));
        columnBinding.setColumnName("Finalidade");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${mvnusua}"));
        columnBinding.setColumnName("Usuário");
        columnBinding.setColumnClass(Integer.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        masterTable.addMouseListener(formListener);
        masterScrollPane.setViewportView(masterTable);
        masterTable.getColumnModel().getColumn(0).setResizable(false);
        masterTable.getColumnModel().getColumn(0).setPreferredWidth(70);
        masterTable.getColumnModel().getColumn(1).setResizable(false);
        masterTable.getColumnModel().getColumn(1).setPreferredWidth(150);
        masterTable.getColumnModel().getColumn(2).setResizable(false);
        masterTable.getColumnModel().getColumn(2).setPreferredWidth(150);
        masterTable.getColumnModel().getColumn(3).setResizable(false);
        masterTable.getColumnModel().getColumn(3).setPreferredWidth(170);
        masterTable.getColumnModel().getColumn(4).setResizable(false);
        masterTable.getColumnModel().getColumn(4).setPreferredWidth(90);
        masterTable.getColumnModel().getColumn(5).setResizable(false);
        masterTable.getColumnModel().getColumn(5).setPreferredWidth(90);
        masterTable.getColumnModel().getColumn(6).setResizable(false);
        masterTable.getColumnModel().getColumn(6).setPreferredWidth(0);
        masterTable.getColumnModel().getColumn(7).setResizable(false);
        masterTable.getColumnModel().getColumn(7).setPreferredWidth(0);
        masterTable.getColumnModel().getColumn(8).setResizable(false);
        masterTable.getColumnModel().getColumn(8).setPreferredWidth(0);
        masterTable.getColumnModel().getColumn(9).setResizable(false);
        masterTable.getColumnModel().getColumn(9).setPreferredWidth(0);
        masterTable.getColumnModel().getColumn(10).setResizable(false);
        masterTable.getColumnModel().getColumn(10).setPreferredWidth(0);
        masterTable.getColumnModel().getColumn(11).setResizable(false);
        masterTable.getColumnModel().getColumn(11).setPreferredWidth(0);

        javax.swing.GroupLayout jPanel5Layout = new javax.swing.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 730, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel5Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(masterScrollPane, javax.swing.GroupLayout.PREFERRED_SIZE, 95, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        minimizarLabel.setFont(new java.awt.Font("Arial", 1, 18));
        minimizarLabel.setForeground(new java.awt.Color(0, 0, 153));
        minimizarLabel.setText("▼");
        minimizarLabel.setToolTipText("Minimizar");
        minimizarLabel.addMouseListener(formListener);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(jPanel5, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())
                    .addComponent(minimizarLabel, javax.swing.GroupLayout.Alignment.TRAILING)))
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addComponent(minimizarLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 9, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(2, 2, 2)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addContainerGap())
        );

        getContentPane().add(jPanel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 780, 490));

        jPanel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jPanel4.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel1.setForeground(new java.awt.Color(0, 0, 153));
        jLabel1.setText("UsuarioLabel");
        jPanel4.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 10, -1, -1));

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel2.setForeground(new java.awt.Color(0, 0, 153));
        jLabel2.setText("Usuário:");
        jPanel4.add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, -1, -1));

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel3.setForeground(new java.awt.Color(0, 0, 153));
        jLabel3.setText("Matrícula:");
        jPanel4.add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, -1, -1));

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel4.setForeground(new java.awt.Color(0, 0, 153));
        jLabel4.setText("MatriculaLabel");
        jPanel4.add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 40, -1, -1));

        logofButton.setFont(new java.awt.Font("Tahoma", 1, 16));
        logofButton.setMnemonic('A');
        logofButton.setText("Alterar Usuário");
        logofButton.addActionListener(formListener);
        jPanel4.add(logofButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 10, -1, -1));

        fecharButton.setFont(new java.awt.Font("Tahoma", 1, 16));
        fecharButton.setMnemonic('F');
        fecharButton.setText("Fechar");
        fecharButton.addActionListener(formListener);
        jPanel4.add(fecharButton, new org.netbeans.lib.awtextra.AbsoluteConstraints(610, 40, -1, -1));

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18));
        jLabel6.setForeground(new java.awt.Color(0, 0, 153));
        jLabel6.setText("CodigoLabel");
        jPanel4.add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(270, 40, -1, -1));

        getContentPane().add(jPanel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 510, 780, 80));

        bindingGroup.bind();

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-800)/2, (screenSize.height-600)/2, 800, 600);
    }

    // Code for dispatching events from components to event handlers.

    private class FormListener implements java.awt.event.ActionListener, java.awt.event.FocusListener, java.awt.event.KeyListener, java.awt.event.MouseListener {
        FormListener() {}
        public void actionPerformed(java.awt.event.ActionEvent evt) {
            if (evt.getSource() == finalidadeField) {
                MovTst.this.finalidadeFieldActionPerformed(evt);
            }
            else if (evt.getSource() == viaturaComboBox) {
                MovTst.this.viaturaComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == motoristaComboBox) {
                MovTst.this.motoristaComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == destinoComboBox) {
                MovTst.this.destinoComboBoxActionPerformed(evt);
            }
            else if (evt.getSource() == newButton) {
                MovTst.this.newButtonActionPerformed(evt);
            }
            else if (evt.getSource() == refreshButton) {
                MovTst.this.refreshButtonActionPerformed(evt);
            }
            else if (evt.getSource() == saveButton) {
                MovTst.this.saveButtonActionPerformed(evt);
            }
            else if (evt.getSource() == logofButton) {
                MovTst.this.logofButtonActionPerformed(evt);
            }
            else if (evt.getSource() == fecharButton) {
                MovTst.this.fecharButtonActionPerformed(evt);
            }
        }

        public void focusGained(java.awt.event.FocusEvent evt) {
        }

        public void focusLost(java.awt.event.FocusEvent evt) {
            if (evt.getSource() == finalidadeField) {
                MovTst.this.finalidadeFieldFocusLost(evt);
            }
        }

        public void keyPressed(java.awt.event.KeyEvent evt) {
            if (evt.getSource() == finalidadeField) {
                MovTst.this.finalidadeFieldKeyPressed(evt);
            }
            else if (evt.getSource() == viaturaComboBox) {
                MovTst.this.viaturaComboBoxKeyPressed(evt);
            }
            else if (evt.getSource() == motoristaComboBox) {
                MovTst.this.motoristaComboBoxKeyPressed(evt);
            }
            else if (evt.getSource() == destinoComboBox) {
                MovTst.this.destinoComboBoxKeyPressed(evt);
            }
        }

        public void keyReleased(java.awt.event.KeyEvent evt) {
        }

        public void keyTyped(java.awt.event.KeyEvent evt) {
        }

        public void mouseClicked(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == viaturaComboBox) {
                MovTst.this.viaturaComboBoxMouseClicked(evt);
            }
            else if (evt.getSource() == motoristaComboBox) {
                MovTst.this.motoristaComboBoxMouseClicked(evt);
            }
            else if (evt.getSource() == destinoComboBox) {
                MovTst.this.destinoComboBoxMouseClicked(evt);
            }
            else if (evt.getSource() == masterTable) {
                MovTst.this.masterTableMouseClicked(evt);
            }
            else if (evt.getSource() == minimizarLabel) {
                MovTst.this.minimizarLabelMouseClicked(evt);
            }
        }

        public void mouseEntered(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == minimizarLabel) {
                MovTst.this.minimizarLabelMouseEntered(evt);
            }
        }

        public void mouseExited(java.awt.event.MouseEvent evt) {
            if (evt.getSource() == minimizarLabel) {
                MovTst.this.minimizarLabelMouseExited(evt);
            }
        }

        public void mousePressed(java.awt.event.MouseEvent evt) {
        }

        public void mouseReleased(java.awt.event.MouseEvent evt) {
        }
    }// </editor-fold>//GEN-END:initComponents

    @SuppressWarnings("unchecked")
    private void refreshButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshButtonActionPerformed

        viaturaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT v FROM Viatura v ");
        MotoristaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM Pessoa p, PessoaTipo t  \nWHERE p.psncodg = t.psncodg  \nAND t.tpncodg = '1' ");
        destinoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT d FROM Destino d");

        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        java.util.Collection data = query.getResultList();
        java.util.Collection dataMt = MotoristaQuery.getResultList();
        java.util.Collection dataVt = viaturaQuery.getResultList();
        java.util.Collection dataDt = destinoQuery.getResultList();
        for (Object entity : data) {
            entityManager.refresh(entity);
        }
        for (Object entity : dataMt) {
            entityManager.refresh(entity);
        }
        for (Object entity : dataVt) {
            entityManager.refresh(entity);
        }
        for (Object entity : dataDt) {
            entityManager.refresh(entity);
        }
        list.clear();
        list.addAll(data);
        MotoristaList.clear();
        MotoristaList.addAll(dataMt);
        viaturaList.clear();
        viaturaList.addAll(dataVt);
        destinoList.clear();
        destinoList.addAll(dataDt);

        this.mvtinicField.setText("");
        this.mvddinicField.setText("");
        this.viaturaComboBox.setSelectedIndex(-1);
        this.motoristaComboBox.setSelectedIndex(-1);
        this.destinoComboBox.setSelectedIndex(-1);

        viaturaComboBox.setEnabled(false);
        motoristaComboBox.setEnabled(false);
        destinoComboBox.setEnabled(false);
        newButton.setEnabled(true);
        refreshButton.setEnabled(false);
        saveButton.setEnabled(false);

        esperarBusyViatura.setEnabled(false);
        esperarBusyMotorista.setEnabled(false);
        esperarBusyDestino.setEnabled(false);
        esperarBusyFinalidade.setEnabled(false);


    }//GEN-LAST:event_refreshButtonActionPerformed
//DELETAR

    private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) {
        int[] selected = masterTable.getSelectedRows();
        List<br.com.sismovimentacao.bean.Movimentacao> toRemove = new ArrayList<br.com.sismovimentacao.bean.Movimentacao>(selected.length);

        int opc;

        for (int idx = 0; idx < selected.length; idx++) {
            br.com.sismovimentacao.bean.Movimentacao m = list.get(masterTable.convertRowIndexToModel(selected[idx]));

            opc = JOptionPane.showConfirmDialog(rootPane, m.getMvcfinl(), "Deseja deletar esse registro?", 2);
            if (opc == 0) {
                toRemove.add(m);
                entityManager.remove(m);
            }
        }
        list.removeAll(toRemove);
        entityManager.getTransaction().commit();
        entityManager.getTransaction().begin();
        refreshButtonActionPerformed(evt);

        //Limpando os campos
        this.mvtinicField.setText("");
        this.mvddinicField.setText("");
        this.viaturaComboBox.setSelectedIndex(-1);
        this.motoristaComboBox.setSelectedIndex(-1);
        this.destinoComboBox.setSelectedIndex(-1);

        viaturaComboBox.setEnabled(false);
        motoristaComboBox.setEnabled(false);
        destinoComboBox.setEnabled(false);
    }
//FIM DELETAR

    @SuppressWarnings("empty-statement")
    private void newButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newButtonActionPerformed
        refreshButtonActionPerformed(evt);
        carregaListaDisponivel();
        viaturaComboBox.setEnabled(true);
        motoristaComboBox.setEnabled(true);
        destinoComboBox.setEnabled(true);
     //   finalidadeField.setEditable(true);
        esperarTempo(120000); // milissegundos

        br.com.sismovimentacao.bean.Movimentacao m = new br.com.sismovimentacao.bean.Movimentacao();
        entityManager.persist(m);
        list.add(m);
        int row = list.size() - 1;
        masterTable.setRowSelectionInterval(row, row);
        masterTable.scrollRectToVisible(masterTable.getCellRect(row, 1, true));
        //Fechado == false
        masterTable.setValueAt(false, row, 0);

        masterTable.setValueAt(jLabel6.getText(), row, 11);

        SimpleDateFormat formataData = new SimpleDateFormat("dd/MM/yyyy");
        this.mvddinicField.setText(formataData.format(new Date()));

        SimpleDateFormat formataHora = new SimpleDateFormat("HH:mm:ss - a");
        this.mvtinicField.setText(formataHora.format(new Date()));

      //  while ()

        this.mvddinicField.grabFocus();
        this.mvtinicField.grabFocus();
        this.viaturaComboBox.grabFocus();
        newButton.setEnabled(false);
        refreshButton.setEnabled(true);
        saveButton.setEnabled(true);

        esperarBusyViatura.setEnabled(true);
        esperarBusyMotorista.setEnabled(true);
        esperarBusyDestino.setEnabled(true);
        esperarBusyFinalidade.setEnabled(true);

    }//GEN-LAST:event_newButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed

        if (this.viaturaComboBox.getSelectedIndex() == -1 || this.motoristaComboBox.getSelectedIndex() == -1 || this.destinoComboBox.getSelectedIndex() == -1 || this.finalidadeField.getText().length() == 0) {
            JOptionPane.showMessageDialog(null, "Necessário informar a viatura, o motorista, o destino e a finalidade!", "Janela", JOptionPane.INFORMATION_MESSAGE);
        } else {
            try {
                entityManager.getTransaction().commit();
                entityManager.getTransaction().begin();
            } catch (RollbackException rex) {
                rex.printStackTrace();
                entityManager.getTransaction().begin();
                List<br.com.sismovimentacao.bean.Movimentacao> merged = new ArrayList<br.com.sismovimentacao.bean.Movimentacao>(list.size());
                for (br.com.sismovimentacao.bean.Movimentacao m : list) {
                    merged.add(entityManager.merge(m));
                }
                list.clear();
                list.addAll(merged);
            }
        }
        refreshButtonActionPerformed(evt);

        //Limpando os campos
        this.mvtinicField.setText("");
        this.mvddinicField.setText("");
        this.viaturaComboBox.setSelectedIndex(-1);
        this.motoristaComboBox.setSelectedIndex(-1);
        this.destinoComboBox.setSelectedIndex(-1);

        viaturaComboBox.setEnabled(false);
        motoristaComboBox.setEnabled(false);
        destinoComboBox.setEnabled(false);
        newButton.setEnabled(true);
        refreshButton.setEnabled(false);
        saveButton.setEnabled(false);

    }//GEN-LAST:event_saveButtonActionPerformed

    private void logofButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_logofButtonActionPerformed

        String args[] = new String[1];
        args[0] = "Identificação do Usuário";
        LoginSenha.main(args);
        dispose();
    }//GEN-LAST:event_logofButtonActionPerformed

    private void fecharButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fecharButtonActionPerformed
        System.exit(0);
}//GEN-LAST:event_fecharButtonActionPerformed

    private void viaturaComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_viaturaComboBoxActionPerformed
        if (masterTable.getSelectedRow() != -1) {
            masterTable.setValueAt(mvnoiniField.getText(), masterTable.getSelectedRow(), 8);
            esperarBusyViatura.setEnabled(false);
        }
    }//GEN-LAST:event_viaturaComboBoxActionPerformed

    private void masterTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_masterTableMouseClicked
        if (newButton.isEnabled()) {
            if (masterTable.getSelectedColumn() == 0) {
                FecharOcorrenciaView fo = new FecharOcorrenciaView(null, true);
                fo.setRegistroAtual(list.get(masterTable.getSelectedRow()));
                fo.carregarCampos(null);
                fo.setVisible(true);
                if (fo.isConfirmaMovimentacao()) {
                    saveButton.setEnabled(true);
                    saveButton.doClick();
                    saveButton.setEnabled(false);
                } else {
                    refreshButton.setEnabled(true);
                    refreshButton.doClick();
                    refreshButton.setEnabled(false);
                }
            } else {
                //
                viaturaComboBox.setEnabled(false);
                destinoComboBox.setEnabled(false);
                destinoComboBox.setEnabled(false);
                newButton.setEnabled(false);
                refreshButton.setEnabled(true);
                saveButton.setEnabled(true);
            }
        } else {
            refreshButtonActionPerformed(null);
        }
    }//GEN-LAST:event_masterTableMouseClicked

    private void finalidadeFieldKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_finalidadeFieldKeyPressed
        String temp = finalidadeField.getText();
        finalidadeField.setText(temp.toUpperCase());
        if (evt.getKeyChar() == '\n') {

            saveButtonActionPerformed(null);
        }
    }//GEN-LAST:event_finalidadeFieldKeyPressed

    private void finalidadeFieldFocusLost(java.awt.event.FocusEvent evt) {//GEN-FIRST:event_finalidadeFieldFocusLost
        String temp = finalidadeField.getText();
        finalidadeField.setText(temp.toUpperCase());
    }//GEN-LAST:event_finalidadeFieldFocusLost

    private void minimizarLabelMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_minimizarLabelMouseClicked
        m.setExtendedState(JFrame.ICONIFIED);
    }//GEN-LAST:event_minimizarLabelMouseClicked

    private void minimizarLabelMouseEntered(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_minimizarLabelMouseEntered
        minimizarLabel.setForeground(Color.red);
    }//GEN-LAST:event_minimizarLabelMouseEntered

    private void minimizarLabelMouseExited(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_minimizarLabelMouseExited
        minimizarLabel.setForeground(Color.BLUE);
    }//GEN-LAST:event_minimizarLabelMouseExited

    private void motoristaComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_motoristaComboBoxActionPerformed
        esperarBusyMotorista.setEnabled(false);
    }//GEN-LAST:event_motoristaComboBoxActionPerformed

    private void destinoComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_destinoComboBoxActionPerformed
        esperarBusyDestino.setEnabled(false);
    }//GEN-LAST:event_destinoComboBoxActionPerformed

    private void finalidadeFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_finalidadeFieldActionPerformed
       esperarBusyFinalidade.setEnabled(false);
    }//GEN-LAST:event_finalidadeFieldActionPerformed

    private void motoristaComboBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_motoristaComboBoxMouseClicked
        motoristaComboBox.grabFocus();
    }//GEN-LAST:event_motoristaComboBoxMouseClicked

    private void destinoComboBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_destinoComboBoxMouseClicked
        destinoComboBox.grabFocus();
    }//GEN-LAST:event_destinoComboBoxMouseClicked

    private void viaturaComboBoxMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_viaturaComboBoxMouseClicked
        viaturaComboBox.grabFocus();
    }//GEN-LAST:event_viaturaComboBoxMouseClicked

    private void viaturaComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_viaturaComboBoxKeyPressed
        if (evt.getKeyChar() == '\n') {
            motoristaComboBox.grabFocus();
        }
    }//GEN-LAST:event_viaturaComboBoxKeyPressed

    private void motoristaComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_motoristaComboBoxKeyPressed
        if (evt.getKeyChar() == '\n') {
            destinoComboBox.grabFocus();
        }
    }//GEN-LAST:event_motoristaComboBoxKeyPressed

    private void destinoComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_destinoComboBoxKeyPressed
        if (evt.getKeyChar() == '\n') {
            finalidadeField.grabFocus();
        }
    }//GEN-LAST:event_destinoComboBoxKeyPressed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List MotoristaList;
    private javax.persistence.Query MotoristaQuery;
    private javax.swing.JComboBox destinoComboBox;
    private java.util.List<br.com.sismovimentacao.bean.Destino> destinoList;
    private br.com.sismovimentacao.renderer.DestinoListCellRenderer destinoListCellRenderer1;
    private javax.persistence.Query destinoQuery;
    private javax.swing.JLabel dtncodgLabel;
    private javax.persistence.EntityManager entityManager;
    private org.jdesktop.swingx.JXBusyLabel esperarBusyDestino;
    private org.jdesktop.swingx.JXBusyLabel esperarBusyFinalidade;
    private org.jdesktop.swingx.JXBusyLabel esperarBusyMotorista;
    private org.jdesktop.swingx.JXBusyLabel esperarBusyViatura;
    private javax.swing.JButton fecharButton;
    private javax.swing.JTextField finalidadeField;
    private static javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private static javax.swing.JLabel jLabel4;
    private static javax.swing.JLabel jLabel6;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JToolBar jToolBar1;
    private java.util.List<br.com.sismovimentacao.bean.Movimentacao> list;
    private javax.swing.JButton logofButton;
    private javax.swing.JScrollPane masterScrollPane;
    private javax.swing.JTable masterTable;
    private javax.swing.JLabel minimizarLabel;
    private javax.swing.JComboBox motoristaComboBox;
    private javax.swing.JLabel mvcfinlLabel;
    private javax.swing.JFormattedTextField mvddinicField;
    private javax.swing.JLabel mvddinicLabel;
    private javax.swing.JTextField mvnoiniField;
    private javax.swing.JLabel mvnoiniLabel;
    private javax.swing.JFormattedTextField mvtinicField;
    private javax.swing.JLabel mvtinicLabel;
    private javax.swing.JButton newButton;
    private br.com.sismovimentacao.renderer.PessoaListCellRenderer pessoaListCellRenderer1;
    private javax.swing.JLabel psncodgLabel;
    private javax.persistence.Query query;
    private javax.swing.JButton refreshButton;
    private javax.swing.JButton saveButton;
    private javax.swing.JComboBox viaturaComboBox;
    private java.util.List<br.com.sismovimentacao.bean.Viatura> viaturaList;
    private br.com.sismovimentacao.renderer.ViaturaListCellRenderer viaturaListCellRenderer1;
    private br.com.sismovimentacao.renderer.ViaturaOdomListRedender viaturaOdomListRedender1;
    private javax.persistence.Query viaturaQuery;
    private javax.swing.JLabel vtncodgLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    public static void main(final String[] args) {
        EventQueue.invokeLater(new Runnable() {

            public void run() {
                m = new MovTst();
                m.setVisible(true);
                jLabel1.setText(args[0]);
                jLabel4.setText(args[1]);
                jLabel6.setText(args[2]);
            }
        });

    }

    public void setMvnofin(String hodometro) {
        try {
            masterTable.setValueAt(hodometro, masterTable.getSelectedRow(), 9);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, e);
        }
    }

    //Carrega a lista de Viaturas, Motoristas e Destinos sem movimentação aberta
    public void carregaListaDisponivel() {


        viaturaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT v FROM Viatura v WHERE v.vtncodg NOT IN  (SELECT DISTINCT m.vtncodg from Movimentacao m WHERE m.mvlfech <> 1 ) ORDER BY v.vtcmodl");
        MotoristaQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT p FROM Pessoa p, PessoaTipo t WHERE p.psncodg = t.psncodg AND t.tpncodg = '1' AND p.psncodg NOT IN ( SELECT DISTINCT m.psncodg from Movimentacao m WHERE m.mvlfech <> 1 ) ORDER BY p.pscdesc");
        destinoQuery = java.beans.Beans.isDesignTime() ? null : entityManager.createQuery("SELECT d FROM Destino d WHERE d.dtncodg NOT IN  ( SELECT DISTINCT m.dtncodg from Movimentacao m WHERE m.mvlfech <> 1 ) ORDER BY d.dtcdesc");

        entityManager.getTransaction().rollback();
        entityManager.getTransaction().begin();
        // this.query.setHint("SELECT m FROM Movimentacao m WHERE m.mvlfech='0'", this);
        java.util.Collection dataMt = MotoristaQuery.getResultList();
        java.util.Collection dataVt = viaturaQuery.getResultList();
        java.util.Collection dataDt = destinoQuery.getResultList();
        for (Object entity : dataMt) {
            entityManager.refresh(entity);
        }
        for (Object entity : dataVt) {
            entityManager.refresh(entity);
        }
        for (Object entity : dataDt) {
            entityManager.refresh(entity);
        }
        MotoristaList.clear();
        MotoristaList.addAll(dataMt);
        viaturaList.clear();
        viaturaList.addAll(dataVt);
        destinoList.clear();
        destinoList.addAll(dataDt);
    }

    public void setMvddfinl() {
        try {
            masterTable.setValueAt(new Date(), masterTable.getSelectedRow(), 7);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(rootPane, new Date(), "Erro ao carregar Data de Fechamento", 1);
        }
    }

    public void teclasDeAtalho() {

        // Some examples of keystrokes
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke("F5"), "Novo");
        getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('\u001b'), "Cancelar");
        //     getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke('\n'), "Salvar");
        getRootPane().getActionMap().put("Novo", new AbstractAction("Novo") {
            // The next two lines should be in one line

            public void actionPerformed(ActionEvent evt) {
                //System.out.println("F5");
                newButtonActionPerformed(evt);
            }
        });
        getRootPane().getActionMap().put("Cancelar", new AbstractAction("Cancelar") {
            // The next two lines should be in one line

            public void actionPerformed(ActionEvent evt) {
                //System.out.println("F5");
                refreshButtonActionPerformed(evt);
            }
        });
        /*getRootPane().getActionMap().put("Salvar", new AbstractAction("Salvar") {
        // The next two lines should be in one line

        public void actionPerformed(ActionEvent evt) {
        //System.out.println("F5");
        saveButtonActionPerformed(evt);
        }
        });*/
    }


    private void esperarTempo(final int time){
       
   //     thread.currentThread().interrupted();
        
        thread = new Thread(new Runnable() {

            public void run() {
                try {
                    Thread.sleep(time);
                } catch (InterruptedException ignored) {
                    Thread.currentThread().interrupt();
                } finally {
                    refreshButtonActionPerformed(null);

                }
            }
        });
        thread.start();

      //  thread.interrupt();

    }
}
